//
//  LoginViewController.m
//  dangdang
//
//  Created by air on 16/1/22.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "UMessage.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(registerPush)];
    
    [self updateUI];
    
    _phoneTextField.delegate = self;
    _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    _phoneTextField.tag = 1;
    _passwordTextField.delegate = self;
    _passwordTextField.secureTextEntry = YES;
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    
    [self.view addGestureRecognizer:singleTap];
    
    self.title = @"登录";
}

-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer

{
    [self.view endEditing:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag == 1) {
        return [self validateNumber:string];
    }
    return YES;
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)updateUI{
    _loginButton.layer.cornerRadius = 8;
    _logoImageView.layer.cornerRadius = _logoImageView.frame.size.width / 2;
    _logoImageView.layer.masksToBounds = YES;
}

- (void)registerPush{
    RegisterViewController * registerboardVC = [[UIStoryboard storyboardWithName:@"RegisterViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"RegisterViewController"];
    [self.navigationController pushViewController:registerboardVC animated:YES];
}

- (IBAction)loginOrForgetBtn:(UIButton *)sender {
    if (sender.tag == 0) {
        if ([_phoneTextField.text isEqual:nil] || [_phoneTextField.text isEqualToString:@""]) {
            [self alertViewShowWithAlertString:@"手机号不能为空"];
            return;
        }
        if ([_passwordTextField.text isEqual:nil] || [_passwordTextField.text isEqualToString:@""]) {
            [self alertViewShowWithAlertString:@"密码不能为空"];
            return;
        }
        NSString * token = userObject.accessToken;
        NSString * passWordString = _passwordTextField.text;
        NSString * phoneString = _phoneTextField.text;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:phoneString forKey:@"phone"];
        [params setObject:passWordString forKey:@"passwd"];
        
        [self postRequestWithMethodName:@"user/identify" andParams:params andSender:nil];
        [LoadingView showInView:self.view image:nil info:@"通讯中，请稍候..." animated:YES modeled:YES autoHide:NO];
    }else{
        RegisterViewController * registerboardVC = [[UIStoryboard storyboardWithName:@"RegisterViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"RegisterViewController"];
        registerboardVC.forgetString = @"forget";
        [self.navigationController pushViewController:registerboardVC animated:YES];
    }
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([code isEqualToString:@"0"]) {
            userObject.userID = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uid"]];
            NSString * plistPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"usersList.plist"];
            NSArray * array = [NSArray arrayWithObject:userObject.userID];
            [array writeToFile:plistPath atomically:YES];
            
            //绑定一下userid
            if(userObject.userID)
            {
                [UMessage addAlias:userObject.userID type:@"userId" response:^(id responseObject, NSError *error) {
                    if(error)
                    {
                        NSLog(@"友盟绑定userId失败,userId = %@",userObject.userID);
                    }
                    else
                        NSLog(@"友盟绑定userId成功,userId = %@",userObject.userID);
                }];
            }

            
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            [self alertViewShowWithAlertString:@"电话号码或密码错误"];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
